-------------------------------------------------------------------------------
-- This file contains the common functions
-------------------------------------------------------------------------------

local mysqlConfFileName = "./conf/serverMYSQL.conf"

local io = require("io")
--require("luarocks.require")
require("luasql.mysql")


-------------------------------------------------------------------------------
-- Execute a command in the database
-------------------------------------------------------------------------------
function db_Execute (cmdString)
	local mysqlParameters = getMysqlParametersFromConfFile()
	local env = assert (luasql.mysql())
	local dbConnect = assert (env:connect(mysqlParameters["database"], mysqlParameters["user"], mysqlParameters["password"], mysqlParameters["hostIP"], mysqlParameters["port"]))

	local execution = dbConnect:execute(tostring(cmdString))

	dbConnect:close()
	env:close()

	return execution
end

-------------------------------------------------------------------------------
-- Get Universally Unique Identifier
-------------------------------------------------------------------------------
function getUUID ()
	local executionStr = string.format([[SELECT uuid()]])
	local execution = db_Execute (executionStr)
	local row = execution:fetch({}, "a")
	return row["uuid()"]
end

-------------------------------------------------------------------------------
-- Crypt a message by a key using algorithmes DES
-------------------------------------------------------------------------------
function crypt(connectToP, key, message)
	local cryptID = getUUID()
	local input = "/home/lebaoanh/crypt/input"..tostring(cryptID)..".txt"
	local output = "/home/lebaoanh/crypt/output"..tostring(cryptID)..".txt"
	
	local file1 = assert(io.open(input, "w"))
    file1:write(tostring(message))
    file1:close()
    
    os.execute(string.format([[openssl enc -des -in '%s' -out '%s' -k '%s']], tostring(input), tostring(output), tostring(key)))

	local file2 = assert(io.open(output, "rb"))
    local cryptedMessage = file2:read("*all")
    file2:close()

--	print("cryptedMessage = "..cryptedMessage)
	
	-- Delete the files input.txt and output.txt
	
	return cryptedMessage
end

-------------------------------------------------------------------------------
-- Decrypt data by key given using the algorithme DES
-------------------------------------------------------------------------------
function decrypt (key, cryptedMessage)
	local decryptID = getUUID()
	local input = "/home/lebaoanh/crypt/input"..tostring(decryptID)..".txt"
	local output = "/home/lebaoanh/crypt/output"..tostring(decryptID)..".txt"
	
	local file1 = assert(io.open(input, "wb"))
    file1:write(cryptedMessage)
    file1:close()

	os.execute(string.format([[openssl enc -d -des -in '%s' -out '%s' -k '%s']], tostring(input), tostring(output), tostring(key)))	
	
	local file2 = assert(io.open(output, "rb"))
    local message = file2:read("*all")
    file2:close()
	
	print("message = "..message)
	
	-- Delete the files input.txt and output.txt
	
	return message
		
end

-------------------------------------------------------------------------------
-- Get parameter function
-------------------------------------------------------------------------------
function getParameter(parameterName)
	local executionStr = string.format([[SELECT * FROM configuration]])
	local execution = db_Execute(executionStr)
	local row = execution:fetch({}, "a")
	return tostring(row[tostring(parameterName)])
end


-------------------------------------------------------------------------------
-- Function get Domain Name Server Web 
-------------------------------------------------------------------------------
function getDomainNameServerWeb()
	return tostring(cgilua.servervariable("SERVER_NAME"))
end

-------------------------------------------------------------------------------
--Function get Port Server Port
-------------------------------------------------------------------------------
function getPortServerWeb()
	return getParameter("WEB_PORT")
end

-------------------------------------------------------------------------------
-- Function get the parameter values from one line in the configure file 
-------------------------------------------------------------------------------
function getValueFromLine(lineStr)
   	local parameter, value = string.match(lineStr, "(%a+)%s*=%s*(.*)")
	return parameter, value
end

-------------------------------------------------------------------------------
-- Function get the MYSQL server parameters from MYSQL configure file
-------------------------------------------------------------------------------
function getMysqlParametersFromConfFile()
	local mysqlParameters = {}
	local mysqlConfFile = assert(io.open(mysqlConfFileName,"r"))
	local line, parameter, value
	-- read MYSQL configure file
	while true do
		line = mysqlConfFile:read("*line")
		if not line then
			break
		end
		parameter, value = getValueFromLine(line)
	
		-- Database
		if (parameter == "Database") then
			mysqlParameters.database = value
		end
		-- User
		if (parameter == "User") then
			mysqlParameters.user = value
		end
		-- Password
		if (parameter == "Password") then
			mysqlParameters.password = value
		end
		-- HostID
		if (parameter == "HostID") then
			mysqlParameters.hostID = value
		end
		-- Port
		if (parameter == "Port") then
			mysqlParameters.port = value
		end
	end
	
	-- Close the MYSQL configure file
	mysqlConfFile:close()
	
	return mysqlParameters
-- End of function getMysqlParametersFromConfFile
end

-------------------------------------------------------------------------------
-- Get IP from String
-------------------------------------------------------------------------------
function getIpFromString(ipString)
	if (#ipString > 8) then	
		local startPosition, endPosition = string.find(ipString, "&")
		if (#string.sub(ipString,startPosition+1) <= 8) then
			return string.sub(ipString,1,startPosition-1), "*"
		else
			return string.sub(ipString,1,startPosition-1), string.sub(ipString,startPosition+1)
		end
--	else
--		return "het roi", "*"
	end
end

